from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from apps.users.models import User
import random
import logging
#from ronglian_sms_sdk import SmsSDK
#from django.conf import settings
from celery_tasks.sms.tasks import sms_send
logger = logging.getLogger('django')
# Create your views here.



# 短信验证码
class SmsMatchView(View):
    def get(self, request, mobile):
        '''短信验证码'''
        # 避免重复发送验证码操作
        redis_conn = get_redis_connection('code')
        # 创建管道
        pl = redis_conn.pipeline()
        mobile_count = redis_conn.get(mobile)
        print(type(mobile_count))
        if mobile_count != None:
            mobile_count = mobile_count.decode()


        # 拿到参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 效验参数
        if mobile_count == '1':
            return JsonResponse({'code': 400,
                                     'errmsg': '手机号重复发送'})
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400,
                                 'errmsg': '数据不全'})
        mobile_count = User.objects.filter(mobile=mobile).count()
        if not mobile_count == 0:
            return JsonResponse({'code': 400,
                                 'errmsg': '手机号重复'})

        image_code_server_b = redis_conn.get('img_%s' % uuid)
        print(type(image_code_server_b))
        if image_code_server_b != None:
            image_code_server = image_code_server_b.decode()
        else:
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码过期'})
        if not image_code_server.lower() == image_code.lower():
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码不正确'})
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)


        # 生成短信验存储
        sms_mobile = '%04d' % random.randint(0, 9999)
        logger.info(sms_mobile)
        try:
            pl.setex('sms_%s' % mobile, 300, sms_mobile)
        except Exception as e:
            logger.error(e)

        # 发送验证码
        # 使用celery异步
        sms_data = (sms_mobile,)
        #sms_send.delay(mobile, sms_data)
        #sdk = SmsSDK(settings.ACCID, settings.ACCTOKEN, settings.APPID)
        #sdk.sendMessage('1', mobile, sms_data)

        # 标记手机号
        pl.setex(mobile, 300, 1)
        # 提交redis
        pl.execute()
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})








# =======================================================================================================

# 图片验证码
class ImageMatchView(View):
    def get(self, request, uuid):

        # 生成图片验证码
            text, image = captcha.generate_captcha()

        # 将文本保存到redis中
            try:
                redis_conn = get_redis_connection('code')
                redis_conn.setex('img_%s' % uuid, 60, text)
            except Exception as e:
                print(e)
                return


        # 返回图片验证码
            return HttpResponse(image, content_type='image/jpeg')






